package com.pangu.config.apollo;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.pangu.config.base.PanguConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Linbizhao
 * @description: 阿波罗配置 @link https://www.apolloconfig.com/#/zh/usage/java-sdk-user-guide?id=_3213-spring-boot%e9%9b%86%e6%88%90%e6%96%b9%e5%bc%8f%ef%bc%88%e6%8e%a8%e8%8d%90%ef%bc%89 [Spring Boot集成Apollo方式]
 * @since 2023/11/18
 */
@Slf4j
@Component
@EnableApolloConfig
public class ApolloConfig implements ApplicationContextAware {

    public static final String NAMESPACE_CONFIG_APPLICATION = "application.properties";

    public static final String NAMESPACE_CONFIG_PANGU = "pangu.yml";

    private ApplicationContext applicationContext;

    @Autowired
    private PanguConfig panguConfig;

    @Autowired
    @Qualifier("configUpdateExecutor")
    private ThreadPoolTaskExecutor configUpdateExecutor;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.applicationContext = context;
    }

    @ApolloConfigChangeListener({NAMESPACE_CONFIG_APPLICATION, NAMESPACE_CONFIG_PANGU})
    private void apolloConfigChangeListener(ConfigChangeEvent event) {
        event.changedKeys().forEach(key -> log.info("Apollo Change Keys:{}", event.changedKeys()));
        applicationContext.publishEvent(new EnvironmentChangeEvent(event.changedKeys()));
        AtomicReference<String> thisEvent = new AtomicReference<>("");
        CompletableFuture<Void> panguConfigInitTask = CompletableFuture.supplyAsync(() -> {
            if (NAMESPACE_CONFIG_PANGU.equals(event.getNamespace())) {
                thisEvent.set("盘古配置");
                // TODO: 2023/11/19 刷新对应配置
                log.info("监控到apollo配置修改事件，自定义扫码配置更新完成");
            }
            return null;
        }, configUpdateExecutor);
    }
}
